package com.lagou.cl.encode;

import com.lagou.cl.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author 程  林
 * @date 2020-05-24 17:10
 * @description // 自定义RPC编码器
 * @since V1.0.0
 */
public class RpcEncoder extends MessageToByteEncoder {

	private Class<?> clazz;

	private Serializer serializer;


	public RpcEncoder(Class<?> clazz, Serializer serializer) {

		this.clazz = clazz;
		this.serializer = serializer;
	}

	@Override
	protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {

		if (clazz != null && clazz.isInstance(msg)) {
			//将数据序列化
			byte[] bytes = serializer.serialize(msg);

			//在当前的{@code writerIndex}处设置指定的32位整数，并在此缓冲区中将{@code writerIndex}增加{@code 4}。
			//如果{@code this.writableBytes}小于{@code 4}，则将调用{@link #ensureWritable（int）}，以尝试扩展容纳的容量
			byteBuf.writeInt(bytes.length);

			//将数据写入byteBuf
			byteBuf.writeBytes(bytes);
		}

	}
}